package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 高亮显示查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class HighlightQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * 标出查询
     */
    @Test
    public void hightlightQuery() throws IOException {
        // 创建查询
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装DSL
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("address", "贵州"));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("address", 100)
                .preTags("</font color='red'>")
                .postTags("</font>");
        // 封装hightlight查询
        builder.highlighter(highlightBuilder);
        request.source(builder);
        // 执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        logger.info("查询DSL:{}", request.source().toString());
        // 输出高亮数据
        logger.info("输出高亮数据");
        for (SearchHit hit : res.getHits().getHits()) {
            HighlightField address = hit.getHighlightFields().get("address");
            logger.info("输出高亮数据：{}", address.getFragments()[0]);
        }
    }
}
